package com.ruoyi.common.utils.file.transfer;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * 远程文件传输工具类 sftp
 *
 * @author ysz
 * @date 2024/6/24 9:52
 */
public class SftpTransferUtil implements FileTransferUtils{
    private static final Logger log = LoggerFactory.getLogger(SftpTransferUtil.class);
    ChannelSftp sftp;

    /**
     * 获取连接
     **/
    @Override
    public boolean getConnection(TransferConnectEntity transferConnectEntity){
        Session session;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(transferConnectEntity.getUsername(), transferConnectEntity.getIp(), transferConnectEntity.getPort());

            if (transferConnectEntity.getPassword() != null) {
                session.setPassword(transferConnectEntity.getPassword());
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (JSchException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取远程文件
     */
    @Override
    public boolean getFile(TransferConnectEntity transferConnectEntity, String remotePath, String remoteFile, String localPath) {
        getConnection(transferConnectEntity);
        if (remotePath == null || "".equals(remotePath)) {
            return false;
        }
        try {
            sftp.cd(remotePath);
            File file = new File(localPath + "/" + remoteFile);
            sftp.get(remoteFile, new FileOutputStream(file));
        } catch (SftpException | FileNotFoundException e) {
            return false;
        } finally {
            if (null != sftp) {
                sftp.disconnect();
            }
        }
        return true;
    }

    /**
     * 远程上传文件
     */
    @Override
    public boolean putFile(TransferConnectEntity transferConnectEntity, String localFile, String remotePath) {
        getConnection(transferConnectEntity);
        FileInputStream fis = null;
        try {
            sftp.cd(remotePath);
        } catch (SftpException e) {
            log.info("没有目录:", remotePath);
            try {
                sftp.mkdir(remotePath);
                sftp.cd(remotePath);
            } catch (SftpException ex) {
                log.info("创建文件目录失败：", remotePath);
                return false;
            }
        }
        try {
            //创建文件流
            fis = new FileInputStream(new File(localFile));
            //上传文件
            sftp.put(fis, localFile.substring(localFile.lastIndexOf(File.separator) + 1));
        } catch (FileNotFoundException | SftpException e) {
            return false;
        } finally {
            if (null != sftp) {
                sftp.disconnect();
            }
        }
        return true;
    }

    @Override
    public boolean putFiles(TransferConnectEntity transferConnectEntity, String localPath, String remotePath) {
        getConnection(transferConnectEntity);
        FileInputStream fis = null;
        try {
            sftp.cd(remotePath);
        } catch (SftpException e) {
            log.info("没有目录:", remotePath);
            try {
                sftp.mkdir(remotePath);
                sftp.cd(remotePath);
            } catch (SftpException ex) {
                log.info("创建文件目录失败：", remotePath);
                return false;
            }
        }
        try {
            File file = new File(localPath);
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    //创建文件流
                    fis = new FileInputStream(files[i]);
                    //上传文件
                    sftp.put(fis, files[i].getName());
                }
            }
        } catch (FileNotFoundException | SftpException e) {
            return false;
        } finally {
            if (null != sftp) {
                sftp.disconnect();
            }
        }
        return true;
    }
}
